import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;

import java.sql.ResultSet;

/**
 * 单个游戏程序
 * @author cxh
 * @date 2022/4/26 16:21
 */
public class GameRunnable implements Runnable{

    /**
     * 游戏次数
     */
    private Integer gameNumber;

    public GameRunnable(Integer gameNumber){
        this.gameNumber = gameNumber;
    }

    @Override
    public void run() {

        //获取当前线程名称
        String roomName = Thread.currentThread().getName();


        if (gameNumber == null || gameNumber <= 0){
            return;
        }

        for (int i = 1; i <= gameNumber; i++) {

            //初始化两名玩家
            GamePlayer gamePlayer1 = new GamePlayer("张三");
            GamePlayer gamePlayer2 = new GamePlayer("李四");

            //随机获取两名玩家的出拳信息
            Integer player1Num = getRandom();
            Integer player2Num = getRandom();
            gamePlayer1.setFinger(player1Num.toString());
            gamePlayer2.setFinger(player2Num.toString());

            GameResult gameResult = fight(gamePlayer1, gamePlayer2,roomName,i);
            GameCollect.dealGameResult(gameResult);

        }

    }

    /**
     * 获取出拳信息
     * @return
     */
    public Integer getRandom(){
        return RandomUtil.randomInt(1,3);
    }

    /**
     * 获取赢家
     * @return
     */
    public GameResult fight(GamePlayer gamePlayer1,GamePlayer gamePlayer2,String roomName,Integer round){

        String player1UserName = gamePlayer1.getUserName();
        String player2UserName = gamePlayer2.getUserName();

        GameResult gameResult = new GameResult();
        gameResult.setRoomName(roomName);
        gameResult.setRound(round);
        gameResult.setPlayer1(gamePlayer1);
        gameResult.setPlayer2(gamePlayer2);

        int result  =  Integer.valueOf(gamePlayer1.getFinger()) - Integer.valueOf(gamePlayer2.getFinger());

        if(result == 0)  {
            gameResult.setWinner("平局");
        }
        else if(result == 1 || result == -2) {
            gameResult.setWinner(player1UserName);
        }
        else if(result == -1 || result == 2) {
            gameResult.setWinner(gamePlayer2.getUserName());
        }

        return gameResult;

    }

}
